package Hot_100;

import java.util.Scanner;

//合并两个有序链表
public class Hot_100_21 {
    /**
     * 值域
     */
    public static class ListNode {
        int val;
        ListNode next;

        public ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        ListNode l1 = new ListNode(-1);
        ListNode l2 = new ListNode(-1);
        System.out.print("请输入l1链表节点个数: ");
        int m = sc.nextInt();
        System.out.print("输入l1节点值: ");
        l1 = Create(m);
        System.out.print("结果: ");
        Print(l1);
        System.out.println();
        System.out.print("请输入l2链表节点个数: ");
        int n = sc.nextInt();
        System.out.print("输入l2节点值: ");
        l2 = Create(n);
        System.out.print("结果: ");
        Print(l2);
        System.out.println();
        System.out.println("合并链表l1、l2: ");
        ListNode l3 = new ListNode(-1);
        l3 = Merge(l1, l2);
        System.out.print("结果: ");
        Print(l3);
    }
    /**
     * 创建链表函数
     *
     * @param n
     * @return
     */
    public static ListNode Create(int n) {
        Scanner sc = new Scanner(System.in);
        //定义投节点
       ListNode head = new ListNode(-1);
       ListNode p = head, q = head;
        //给头节点赋值
        p.val = sc.nextInt();
        n--;
        //依次赋值，形成链
        while (n > 0) {
            q = p;
            p = new ListNode(-1);
            p.val = sc.nextInt();
            q.next = p;
            n--;
        }
        return head;
    }
    /**
     * 合并链表函数
     *
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode Merge(ListNode l1, ListNode l2) {
        //定义虚拟指针
        ListNode pre = new ListNode(-1);
        ListNode cur = pre;
        //遍历l1,l2
        while (l1 != null && l2 != null) {
            //如果l1当前节点比l2当前节点小，则入链
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                //如果l1当前节点比l2当前节点>，则入链
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        //l1还有节点则直接连接
        if (l1 != null) {
            cur.next = l1;
        }
        //l2还有节点则直接连接
        if (l2 != null) {
            cur.next = l2;
        }
        return pre.next;
    }
    /**
     * 输出链表元素函数
     *
     * @param head
     */
    public static void Print(ListNode head) {
        for (ListNode p = head; p != null; p = p.next) {
            System.out.print(p.val + " ");
        }
    }
}
//时间复杂度: O(n)
//空间复杂度: O(1)